<template>
  <div class="container dark-theme">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="logo">“沈誉通”信用生活综合系统</div>
      <div class="nav">
        <!-- <router-link to="/home">首页</router-link> -->
        <router-link to="/credit-life">信用生活</router-link>
        <router-link to="/credit-business">信用商业</router-link>
        <router-link to="/behavior">亲社会行为</router-link>
        <router-link to="/news">新闻资讯</router-link>
        <router-link to="/credit-management">信用管理</router-link>
      </div>
      <div class="user-menu" ref="userMenu">
        <div class="avatar-box">
          <img
            :src="user.icon || require('@/imgs/icons/default-icon.png')"
            class="avatar"
            alt="用户头像"
            @click.stop="toggleMenu"
          />
        </div>
        <div v-if="isMenuOpen" class="dropdown-menu">
          <div class="menu-item" @click="goToProfile">个人信息</div>
          <div class="menu-item" @click="logout">退出登录</div>
        </div>
      </div>
    </div>

    <!-- 实名认证卡片 -->
    <el-card class="box-card">
      <h2 class="card-title">实名认证</h2>
      <el-form
        :model="verifyForm"
        :rules="verifyRules"
        ref="verifyFormRef"
        label-width="150px"
        :disabled="isVerified"
      >
        <el-form-item label="真实姓名" prop="realName">
          <el-input
            v-model="verifyForm.realName"
            class="sci-fi-input"
            placeholder="请输入真实姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input
            v-model="verifyForm.idNumber"
            class="sci-fi-input"
            placeholder="请输入身份证号"
          ></el-input>
        </el-form-item>

        <el-form-item label="认证时间" v-if="isVerified">
          <el-input
            :value="formatDate(verifyForm.createTime)"
            class="sci-fi-input"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!isVerified">
          <el-button
            type="primary"
            class="sci-fi-button"
            @click="submitVerification"
          >
            提交认证
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Verification',
  data() {
    // 自定义身份证号验证规则
    const validateIdNumber = (rule, value, callback) => {
      const reg = /(^\d{17}(\d|X|x)$)/;
      if (!value) {
        callback(new Error('请输入身份证号'));
      } else if (!reg.test(value)) {
        callback(new Error('请输入有效的18位身份证号'));
      } else {
        callback();
      }
    };

    return {
      user: {
        icon: '',
      },
      isMenuOpen: false,
      isVerified: false,
      verifyForm: {
        realName: '',
        idNumber: '',
        createTime: '',
      },
      verifyRules: {
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '姓名长度在2到10个字符',
            trigger: 'blur',
          },
        ],
        idNumber: [
          { required: true, validator: validateIdNumber, trigger: 'blur' },
        ]
      },
    };
  },
  created() {
    this.getUserInfo();
    this.getVerificationStatus();
  },
  methods: {
    toggleMenu() {
      this.isMenuOpen = !this.isMenuOpen;
    },
    closeMenuOnClickOutside(event) {
      const menu = this.$refs.userMenu;
      if (menu && !menu.contains(event.target)) {
        this.isMenuOpen = false;
      }
    },
    goToProfile() {
      this.$router.push('/user-information');
      this.isMenuOpen = false;
    },
    logout() {
      axios
        .post('/users/user/logout')
        .then(() => {
          localStorage.removeItem('token');
          this.$router.push('/login-code');
        })
        .catch((err) =>
          this.$message.error('退出登录失败：' + err.message)
        );
    },
    async getUserInfo() {
      try {
        const { data } = await axios.get('/users/user/basic', {
          headers: { Authorization: `${localStorage.getItem('token')}` },
        });
        if (data.success && data.data) {
          this.user = data.data;
        }
      } catch (err) {
        this.$message.error('获取用户信息失败：' + err.message);
      }
    },
    async getVerificationStatus() {
      try {
        const { data } = await axios.get('/users/user-info/status', {
          headers: { Authorization: `${localStorage.getItem('token')}` },
        });
        if (data.success && data.data) {
          this.isVerified = true;
          this.verifyForm = {
            realName: data.data.realName,
            idNumber: data.data.idNumber,
            createTime: data.data.createTime,
          };
        } else {
          this.isVerified = false;
        }
      } catch (err) {
        this.$message.error('获取认证状态失败：' + err.message);
      }
    },
    submitVerification() {
      this.$refs.verifyFormRef.validate(async (valid) => {
        if (!valid) return;
        try {
          const { data } = await axios.post('/users/user-info', this.verifyForm, {
            headers: { Authorization: `${localStorage.getItem('token')}` },
          });
          if (data.success) {
            this.$message.success('实名认证成功！');
            await this.getVerificationStatus();
          } else {
            this.$message.error('实名认证失败：' + data.errorMsg);
          }
        } catch (err) {
          this.$message.error('实名认证失败：' + err.message);
        }
      });
    },
    formatDate(date) {
      if (!date) return '';
      return new Date(date).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      });
    },
  },
};
</script>

<style scoped>
.container {
  width: 100%;
  min-height: 100vh;
  background: radial-gradient(ellipse at center, #001e3c 0%, #000 100%);
  color: #fff;
  font-family: 'Microsoft YaHei', sans-serif;
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  padding: 10px 30px;
  background: #002d52;
  align-items: center;
}

.logo {
  font-size: 20px;
  color: #4fc3f7;
}

.nav a {
  margin: 0 10px;
  color: #fff;
  text-decoration: none;
}

.nav a:hover {
  color: #4fc3f7;
}

.user-menu {
  position: relative;
}

.avatar-box img.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #4fc3f7;
}

.dropdown-menu {
  position: absolute;
  top: 50px;
  right: 0;
  width: 120px;
  background: #002d52;
  border: 1px solid #4fc3f7;
  border-radius: 4px;
  z-index: 10;
}

.menu-item {
  padding: 10px;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
}

.menu-item:hover {
  background: #014b75;
}

.box-card {
  margin: 20px;
  background: #13263a;
  border-radius: 10px;
}

.card-title {
  color: #4fc3f7;
  font-size: 24px;
  margin-bottom: 20px;
  text-align: center;
}

.sci-fi-input .el-input__inner {
  background: #001e3c;
  border: 1px solid #4fc3f7;
  color: #fff;
}

.sci-fi-select .el-input__inner {
  background: #001e3c;
  border: 1px solid #4fc3f7;
  color: #fff;
}

.sci-fi-button {
  background: #00ccff;
  border: none;
  color: #001c3e;
}

.sci-fi-button:hover {
  background: #014b75;
}
</style>
